package com.yanwq.sayhi.common.client;

import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.sayhi.MApplication;
import com.yanwq.sayhi.widget.MToast;

/**
 * 作者：yanweiqiang。
 * 日期：2016/6/20 0020。
 */
public class FailureResultTool {

    public static void handle(int status, String s, Throwable throwable) {
        StringBuilder builder = new StringBuilder();
        builder.append("status:").append(status);
        builder.append(" | ");
        builder.append("message:");

        JSONObject jsonObject = null;
        try {
            jsonObject = JSON.parseObject(s);

            if (TextUtils.isEmpty(s)) {
                builder.append(throwable.getMessage());
            } else if (jsonObject.containsKey("msg")) {
                builder = new StringBuilder();
                builder.append(jsonObject.getString("msg"));
            } else if (jsonObject.containsKey("message")) {
                builder.append(jsonObject.getString("message"));
            }
        } catch (JSONException ignore) {
            builder.append(s);
        }

        if (MApplication.debug) {
            Toast.makeText(MApplication.getContext(), builder.toString(), Toast.LENGTH_SHORT).show();
        } else {
            if (status == 0) {
                Toast.makeText(MApplication.getContext(), "网络不给力", Toast.LENGTH_SHORT).show();
            } else if (status == 404) {
                Toast.makeText(MApplication.getContext(), "服务器不堪重负，逃跑了", Toast.LENGTH_SHORT).show();
            } else {
                if (jsonObject != null && jsonObject.containsKey("msg")) {
                    Toast.makeText(MApplication.getContext(), builder.toString(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MApplication.getContext(), "服务器生气了", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
